#region (c) 2014 Nguyễn, M. Hải - All rights reserved
/*
BLADE VIEW ENGINE

The MIT License (MIT)
Copyright (c) 2014 Nguyễn, M. Hải

Permission is hereby granted, free of charge, to any person obtaining a copy of this 
software and associated documentation files (the "Software"), to deal in the Software 
without restriction, including without limitation the rights to use, copy, modify, merge
, publish, distribute, sublicense, and/or sell copies of the Software, and to permit 
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
 substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
DEALINGS IN THE SOFTWARE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 26-Apr-14 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;

using Thn;
using Thn.IO;
using Thn.Web;
using Thn.Web.Mvc;
using Thn.Collections;
using System.IO;
#endregion

namespace Thn.Web.Blade
{
    /// <summary>
    /// Implementation of <see cref="IViewRenderer"/> using BLADE.
    /// </summary>
    [ImplementContract(ContractType = typeof(IViewRenderer))]
#if DEBUG || TESTING
    public
#else
    public
#endif
 class BladeViewRenderer : IViewRenderer
    {
        #region Fields
        /// <summary>
        /// Cache of known template types by view name.
        /// </summary>
        StringDictionary<Type> mTemplates = new StringDictionary<Type>();
        #endregion

        #region Properties

        #region Path Translator
        private IPathTranslator mPathTranslator;
        /// <summary>
        /// Gets or sets the translator responsible for resolving paths.
        /// </summary>
        public IPathTranslator PathTranslator
        {
            get { return mPathTranslator; }
            set { mPathTranslator = value; }
        }
        #endregion

        #endregion

        #region Get View
        ViewTemplate GetView(string viewName)
        {
            ViewTemplate result;

            //look up from cache first
            Type viewType = mTemplates[viewName];

            //build type if not in cache yet
            if (viewType == null)
            {
                #region Not found in cache -> read file and compile

                //translate to local path
                string filename = mPathTranslator.Translate("/" + viewName);

                //append file extensions
                filename += ".cshtml";

                //read from file
                string template = File.ReadAllText(filename);

                //compile
                var compiler = new BladeCodeCompiler();
                compiler.ParseAndCompile(template);
                compiler.SilentError = false;
                viewType = compiler.CompiledType;

                #endregion
            }

            //create result
            if (viewType != null)
            {
                result = (ViewTemplate)Activator.CreateInstance(viewType);
                result.Renderer = this;
            }
            else result = null;

            return result;
        }
        #endregion

        #region IViewRenderer Members

        #region Render
        /// <summary>
        /// Render a specific view.
        /// </summary>
        void IViewRenderer.Render(RenderArgs args)
        {
            //get template
            ViewTemplate template = GetView(args.ViewName);

            //set model
            template.Model = args.Model;

            //set writer
            template.Writer = args.Writer;

            //set context
            template.Context = args.Context;

            //execute template
            template.Execute();            
        }
        #endregion

        #endregion

        #region Constructors
        /// <summary>
        /// Create a new instance.
        /// </summary>
        public BladeViewRenderer()
            : base()
        { }
        #endregion
    }
}
